/**
 * 
 */
package com.geekteam.geometrychess.handler.request.game;

import com.geekteam.geometrychess.extension.ChessExtension;
import com.geekteam.geometrychess.handler.request.BaseRequestHandler;
import com.geekteam.geometrychess.utils.Code;
import com.geekteam.geometrychess.utils.Commands;
import com.geekteam.geometrychess.utils.Constants.Key;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;

/**
 * @author MtRol
 * 
 */
public class StartGameRequestHandler extends BaseRequestHandler {

	@Override
	public void handleClientRequest(User user, ISFSObject sfsObject) {
		mRoom = user.getLastJoinedRoom();
		mExtension = (ChessExtension) getParentExtension();
		mGameBoard = mExtension.getBoard(mRoom.getId());

		if (mRoom.isGame()) {
			if (mGameBoard == null) {
				mExtension.sendPrivateError(Code.GAME_BOARD_NULL,
						"game board null", user.getId());
				return;
			}

			if (mGameBoard.getRoomBoard().isPlaying()) {
				mExtension.sendPrivateError(Code.GAME_IS_PLAYING,
						"game is playing", user.getId());
				return;
			}

			if (mGameBoard.getRoomBoard().getNumberPlayerInRoom() != 2) {
				mExtension.sendPrivateError(Code.NEED_MORE_PLAYER,
						"need more player", user.getId());
				return;
			}

			if (!mGameBoard.getRoomBoard().isOwner(user.getId())) {
				mExtension.sendPrivateError(Code.YOU_NOT_OWNER,
						"you not owner", user.getId());
				return;
			}

			int idStart = mGameBoard.getRoomBoard().getStartId();
			if (idStart == -1) {
				mExtension.sendPrivateError(Code.NOT_FOUND_STARTER,
						"not found starter", user.getId());
				return;
			}
			// TODO check ready of player before start
			
			mResultObject = new SFSObject();
			mResultObject.putInt(Key.CODE, Code.SUCCESS);
			mResultObject.putUtfString(Key.MESSAGE, "game start");
			mResultObject.putInt(Key.ID_START, idStart);
			mResultObject.putInt(Key.TIME_TOTAL, mGameBoard.getConfig().mTimeTotal);
			mResultObject.putInt(Key.TIME_TURN, mGameBoard.getConfig().mTimeTurn);
			
			send(Commands.START_GAME, sfsObject, mRoom.getUserList());
			mGameBoard.getRoomBoard().setPlaying(true);
			mGameBoard.getRoomBoard().setTurn(idStart);
			
			// TODO set timer here

		} else {
			mExtension.sendPrivateError(Code.ROOM_NOT_GAME, "room not game",
					user.getId());
		}
	}

}
